<template>
  <div class="login-page">
  <el-card class="login">
    <h2>登录</h2>
    <el-form 
      :model="loginForm" 
      ref="loginFormRef" 
      :rules="rules" 
      label-width="80px" 
      @submit.prevent="handleLogin"
      :disabled="isLocked"
    >
      <el-form-item label="用户名" prop="username">
        <el-input 
        v-model="loginForm.username"
        autocomplete="username" />
      </el-form-item>
      <el-form-item label="密码" prop="password" >
        <el-input 
        v-model="loginForm.password"
        type="password" 
        autocomplete="current-password" 
        show-password/>
      </el-form-item>
      <el-form-item>
        <el-checkbox v-model="loginForm.rememberMe">记住我</el-checkbox>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit" :loading="loading" @click.prevent="handleLogin">登录</el-button>
      </el-form-item>
      <el-form-item v-if="errorMsg && !isLocked">
        <el-alert :title="errorMsg" type="error" show-icon />
      </el-form-item>
      <!-- 锁定提示 -->
      <el-form-item v-if="isLocked">
        <el-alert 
          :title="`账号已锁定，剩余 ${formatLockTime(remainingTime)}`" 
          type="warning" 
          show-icon 
        />
      </el-form-item>
    </el-form>
    <div class="register-link">
      没有账号？
      <a @click.prevent="goRegister" href="#">去注册</a>
    </div>
  </el-card>
  </div>
</template>

<script setup>
import { ref, computed, watch, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'  // 新增：引入useRoute
import { useAuthStore } from '@/stores/auth'
import authApi from '../../api/auth'

const router = useRouter()
const route = useRoute()  // 新增：获取当前路由信息
const authStore = useAuthStore()

const loginFormRef = ref(null)
const loginForm = ref({
  username: '',
  password: '',
  rememberMe: false
})
const loading = ref(false)
const errorMsg = ref('')

// 锁定相关配置
const LOCK_THRESHOLD = 5  // 5次失败后锁定
const LOCK_DURATION = 30 * 60 * 1000  // 锁定30分钟（毫秒）

// 从localStorage加载状态
const loadState = (username) => {
  const key = `loginState_${username}`
  const saved = localStorage.getItem(key)
  return saved ? JSON.parse(saved) : {
    failCount: 0,        // 失败次数
    lockStartTime: 0     // 锁定开始时间戳
  }
}

// 保存状态到localStorage
const saveState = (username, state) => {
  const key = `loginState_${username}`
  localStorage.setItem(key, JSON.stringify(state))
}

// 状态管理
const loginState = ref(loadState(loginForm.value.username))

// 计算是否处于锁定状态
const isLocked = computed(() => {
  if (loginState.value.lockStartTime === 0) return false
  return Date.now() - loginState.value.lockStartTime < LOCK_DURATION
})

// 剩余锁定时间（毫秒）
const remainingTime = ref(0)
let lockTimer = null

// 格式化锁定时间为秒
const formatLockTime = (ms) => {
  const minutes = Math.floor(ms / (60 * 1000))
  const seconds = Math.ceil((ms % (60 * 1000)) / 1000)
  return `${minutes}分${seconds}秒`
}

// 启动锁定倒计时
const startLockTimer = () => {
  if (lockTimer) clearInterval(lockTimer)
  
  const updateRemaining = () => {
    const now = Date.now()
    const remaining = LOCK_DURATION - (now - loginState.value.lockStartTime)
    
    if (remaining <= 0) {
      // 锁定时间结束，重置状态
      loginState.value = { failCount: 0, lockStartTime: 0 }
      saveState(loginForm.value.username, loginState.value)
      remainingTime.value = 0
      clearInterval(lockTimer)
      return
    }
    remainingTime.value = remaining
  }
  
  updateRemaining()
  lockTimer = setInterval(updateRemaining, 1000)
}

// 监听用户名变化，加载对应用户的状态
watch(
  () => loginForm.value.username,
  (newUsername) => {
    if (lockTimer) clearInterval(lockTimer)
    loginState.value = loadState(newUsername)
    if (isLocked.value) {
      startLockTimer()
    }
  },
  { immediate: true }
)

// 组件卸载时清理定时器
onUnmounted(() => {
  if (lockTimer) clearInterval(lockTimer)
})

const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

const handleLogin = async () => {
  // 锁定状态直接返回
  if (isLocked.value) {
     router.push('/login')
    return
  }
  loading.value = true
  errorMsg.value = ''  
  try {
    let logUser = {
      Username:loginForm.value.username,
      Password:loginForm.value.password
    }
    // 调用后端登录接口
     const response = await authApi.login(logUser);   
     const userData = response.userInfo
    const token = response.data?.token || response.token
    // 关键修改：通过store设置用户数据
      authStore.setAuthData({
      user: {
        Username: userData.username || userData.Username,
        Email: userData.email || userData.Email,
        // Phone: userData.phone || userData.Phone,
        // 其他字段...
      },
      token: token
    })
    // 登录成功：重置失败次数
    loginState.value = { failCount: 0, lockStartTime: 0 }
    saveState(loginForm.value.username, loginState.value)
    
    // 关键修改：跳转到之前的页面（优先使用redirect参数）
    const redirectPath = route.query.redirect || '/dashboard'   
    router.push(redirectPath)
    
  } catch (error) {
    // 登录失败处理（如果需要使用错误信息，可以保留error参数）
    loginState.value.failCount += 1
    const remainingAttempts = LOCK_THRESHOLD - loginState.value.failCount
    
    if (loginState.value.failCount >= LOCK_THRESHOLD) {
      loginState.value.lockStartTime = Date.now()
      saveState(loginForm.value.username, loginState.value)
      startLockTimer()
      errorMsg.value = ''
    } else {
      errorMsg.value = `用户名或密码错误，已失败${loginState.value.failCount}次，再失败${remainingAttempts}次将锁定30分钟`
      saveState(loginForm.value.username, loginState.value)
    }
  } finally {
    loading.value = false
  }
}


const goRegister = () => {
  router.push('/register')
}
</script>

<style scoped>
.login-page {
  background: #304156;
  background-size: cover;
  background-position: center;
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.login {
  width: 400px;
  padding: 30px;
  background-color: rgba(255, 255, 255, 0.871);
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15), 
              0 5px 15px rgba(0, 0, 0, 0.1), 
              0 2px 5px rgba(0, 0, 0, 0.05);
  border-radius: 12px;
  backdrop-filter: blur(5px); 
}

.register-link {
  margin-top: 16px;
  text-align: center;
  color: #666;
}
.register-link a {
  color: #409EFF;
  cursor: pointer;
  margin-left: 4px;
  text-decoration: underline;
}
</style>
    